<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="主任务名称" prop="mainTaskName">
        <TaskTitleSelect
          v-model="queryParams.taskTitle"
          @change="handleTaskTitleChange"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="执行人" prop="operatorUserId">
        <UserSelect
          v-model="queryParams.operatorUserId"
          @node-change="handleUserChange"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="执行人" prop="operatorUserName" v-show="false">
        <el-input v-model="queryParams.operatorUserName" />
      </el-form-item>
      <el-form-item label="优先级" prop="priorityType">
        <el-select
          v-model="queryParams.priorityType"
          placeholder="请选择优先级"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.OA_PRIORITY_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务状态" prop="taskStatus">
        <el-select
          v-model="queryParams.taskStatus"
          placeholder="请选择任务状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.OA_TASK_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <!-- <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['oa:subtasks:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button> -->
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['oa:subtasks:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!-- <el-table-column label="序号" align="center" prop="id" /> -->
      <el-table-column label="主任务名称" align="center" prop="mainTaskName" />

      <el-table-column label="子任务名称" align="center" prop="taskTitle" />
      <el-table-column label="执行人" align="center" prop="operatorUserName" />
      <el-table-column label="优先级" align="center" prop="priorityType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.OA_PRIORITY_TYPE" :value="scope.row.priorityType" />
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="endDate" />
      <el-table-column label="实际完成日期" align="center" prop="actualEndDate" width="129" />
      <el-table-column label="主任务状态" align="center" prop="mainTaskStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.OA_TASK_STATUS" :value="scope.row.mainTaskStatus" />
        </template>
      </el-table-column>
      <el-table-column label="子任务状态" align="center" prop="taskStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.OA_TASK_STATUS" :value="scope.row.taskStatus" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="创建人" align="center" prop="createName" />
      <el-table-column label="操作" align="center" width="120" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="viewMainTask(scope.row.mainTaskId)"
            v-if="scope.row.mainTaskId"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <SubtasksForm ref="formRef" @success="getList" />
  <!-- 拒绝理由弹窗 -->
  <el-dialog v-model="showRejectDialog" title="拒绝理由" width="400px">
          <el-form>
            <el-form-item label="理由" required>
              <el-input
                v-model="rejectReason"
                type="textarea"
                :rows="4"
                maxlength="200"
                show-word-limit
                placeholder="请输入拒绝理由"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="showRejectDialog = false">取消</el-button>
            <el-button type="primary" @click="submitRejectReason">确定</el-button>
          </template>
        </el-dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { SubtasksApi, SubtasksVO } from '@/api/oa/subtasks'
import SubtasksForm from './SubtasksForm.vue'
import TaskTitleSelect from '@/components/TaskTitleSelect/index.vue'
import UserSelect from '@/views/system/user/UserSelect.vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/modules/user'

/** 子任务管理 列表 */
defineOptions({ name: 'Subtasks' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const router = useRouter() // 路由对象
const userStore = useUserStore()

const loading = ref(true) // 列表的加载中
const list = ref<SubtasksVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  taskTitle: undefined as string | undefined,
  mainTaskId: undefined ,
  operatorUserId: undefined as number | undefined,
  operatorUserName: undefined as string | undefined,
  priorityType: undefined as number | undefined,
  taskStatus: undefined as number | undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const requestParams = {
      ...queryParams,
      mainTaskId: queryParams.mainTaskId?.id, // 只传递 id 给后端
    };
    const data = await SubtasksApi.getSubtasksPageAll(requestParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.mainTaskId = undefined // 手动清空 mainTaskId
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await SubtasksApi.deleteSubtasks(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await SubtasksApi.exportSubtasks(queryParams)
    download.excel(data, '子任务管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 处理任务主题变更 */
const handleTaskTitleChange = (mainTaskId: number) => {
  queryParams.mainTaskId = mainTaskId
}

/** 处理执行人变更 */
const handleUserChange = (user: any) => {
  if (user) {
    queryParams.operatorUserId = user.id
    queryParams.operatorUserName = user.nickname
  } else {
    queryParams.operatorUserId = undefined
    queryParams.operatorUserName = undefined
  }
}

/** 新增查看主任务方法 */
const viewMainTask = (mainTaskId: number) => {
  if (!mainTaskId) {
    message.warning('未找到主任务ID')
    return
  }
  router.push({ name: 'MainTasksDetail', query: { id: mainTaskId } })
}

const handleFinishSubtask = async (id: number, taskStatus: number) => {
  await ElMessageBox.confirm('确定修改改子任务状态吗？', '提示', { type: 'warning' });
  await SubtasksApi.updateTasksStatus(id,2, taskStatus,'');
  getList();
};

const showRejectDialog = ref(false)
const rejectReason = ref('')
const rejectSubtaskRow = ref<SubtasksVO | null>(null)
const openRejectDialog = (row: SubtasksVO) => {
  rejectSubtaskRow.value = { ...row }
  rejectReason.value = ''
  showRejectDialog.value = true
}

const submitRejectReason = async () => {
  if (!rejectReason.value.trim()) {
    message.warning('请填写拒绝理由')
    return
  }
  try {
    if (!rejectSubtaskRow.value || typeof rejectSubtaskRow.value.id !== 'number') {
      message.error('子任务数据异常')
      return
    }

    await SubtasksApi.updateTasksStatus(rejectSubtaskRow.value.id,2, 2,rejectReason.value);
    message.success('操作成功')
    showRejectDialog.value = false
    getList()
  } catch (e) {
    // 错误处理
  }
}
/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
